package com.ruoyi.wapp.controller.base;

import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WdyUser;
import com.ruoyi.wapp.util.MyConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public abstract class BaseController{
	protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected RedisTemplate redisTemplate;

    @Autowired
    protected Environment environment;
    /** 基于@ExceptionHandler异常处理 */
    @ExceptionHandler
    @ResponseBody
    public Result handleAndReturnData(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("业务异常捕获", e);
        BusinessException be =null;//业务异常捕获
        if(e instanceof  BusinessException) be = (BusinessException)e;
        Result result;
        if(be != null){
            result = Result.error(be.getCode(), be.getMessage());
        } else{
            log.error("程序异常", e);
            result = Result.error(ResultConstants.EX9999,MessageUtils.message("system.error"));
        }
        return result;
    }

    /**
     * @Title: 获取在线用户，返回null代表无登录
     * @Description: 系统中抛出的业务异常捕获(这里用一句话描述这个方法的作用)
     * @param @return    设定文件
     * @return WJException    返回类型
     * @throws
     */
    protected WdyUser getOnlineMember(){
        HttpServletRequest request = getHttpServletRequest();
        WdyUser user = (WdyUser) request.getAttribute(MyConstants.CONFIG.RUQUEST_MEMBER_NAME);
        return user;
    }

    /**
     * 获取token
     * @return
     */
    protected String getToken() {
        HttpServletRequest request = getHttpServletRequest();
        String token = request.getHeader(MyConstants.CONFIG.TOKEN_HEAD_NAME);
        return token;
    }

    protected HttpServletRequest getHttpServletRequest() {
        return ((org.springframework.web.context.request.ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 是否生产环境
     * @return
     */
    protected boolean isProdEnv() {
        String property = environment.getProperty("spring.profiles.active");
        if(StringUtils.isNotEmpty(property) && property.contains("prod")) {
            return true;
        }
        return false;
    }

}
